<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';

import * as echarts from 'echarts';

const chartRef = ref<HTMLElement>();
let chartInstance: echarts.ECharts | null = null;

onMounted(() => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);

    const option = {
      title: {
        text: '国库收支趋势',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: ['收入', '支出', '结余'],
        bottom: 0,
      },
      xAxis: {
        type: 'category',
        data: [
          '洪武元年',
          '洪武十年',
          '建文元年',
          '永乐元年',
          '永乐十年',
          '宣德元年',
        ],
      },
      yAxis: {
        type: 'value',
        name: '万两',
      },
      series: [
        {
          name: '收入',
          type: 'line',
          data: [1000, 1500, 1800, 2500, 3000, 2800],
          smooth: true,
          itemStyle: { color: '#52c41a' },
        },
        {
          name: '支出',
          type: 'line',
          data: [800, 1200, 1500, 2000, 2300, 1800],
          smooth: true,
          itemStyle: { color: '#ff4d4f' },
        },
        {
          name: '结余',
          type: 'bar',
          data: [200, 300, 300, 500, 700, 1000],
          itemStyle: { color: '#1890ff' },
        },
      ],
    };

    chartInstance.setOption(option);

    // 响应式
    window.addEventListener('resize', handleResize);
  }
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  chartInstance?.dispose();
});

function handleResize() {
  chartInstance?.resize();
}
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 300px"></div>
</template>
